<?php

	// +----------------------------------------------------------------------
	// | 菜单模型
	// +----------------------------------------------------------------------
	// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
	// +----------------------------------------------------------------------
	// | Author: 微尘 <yicmf@qq.com>
	// +----------------------------------------------------------------------

	namespace app\model\admin;

	class Menu extends Common
	{

		/**
		 * 模块安装时进行菜单注册.
		 * @param array $data 菜单数据
		 * @param array $config 模块配置
		 * @param type $parentid 父菜单ID
		 * @return bool
		 */
		public function installModuleMenu(array $data, array $config, $parentid = 0)
		{
			if (empty($data) || !is_array($data)) {
				$this->error = '没有数据！';
				return false;
			}
			if (empty($config)) {
				$this->error = '模块配置信息为空！';
				return false;
			}
			// 默认安装时父级ID
			$defaultMenuParentid = 0;
			// 安装模块名称
			$moduleNama = $config['module'];
			foreach ($data as $rs) {
				if (empty($rs['route'])) {
					$this->error = '菜单信息配置有误，route 不能为空！';
					return false;
				}
				$route = $this->menuRoute($rs['route']);
				$pid = $parentid ?: ((is_null($rs['pid']) || !isset($rs['pid'])) ? (int)$defaultMenuParentid : $rs['pid']);
				$newData = array_merge([
					'title' => $rs['title'],
					'pid' => $pid,
					'sort' => isset($rs['sort']) ? ($rs['sort'] + 100) : 100,
					'hide' => isset($rs['hide']) ? $rs['hide'] : 0,
					'tips' => $rs['tips'],
					'group' => $rs['group'],
					'is_dev' => isset($rs['is_dev']) ? $rs['is_dev'] : 0,
					'status' => isset($rs['status']) ? $rs['status'] : 0,
					'icon' => $rs['icon']
				], $route);
				if (!$this->create($newData)) {
					$this->error = '菜单信息配置有误，' . $this->error;
					return false;
				}
				$newId = $this->add();
				// 是否有子菜单
				if (!empty($rs['child'])) {
					if ($this->installModuleMenu($rs['child'], $config, $newId) !== true) {
						return false;
					}
				}
			}
			return true;
		}


		/**
		 * 把模块安装时，Menu.php中配置的route进行转换.
		 * @param type $route route内容
		 * @param type $moduleNama 安装模块名称
		 * @return array
		 */
		private function menuRoute($route, $moduleNama)
		{
			$route = explode('/', $route, 3);
			if (count($route) < 3) {
				array_unshift($route, $moduleNama);
			}
			$data = [
				'module' => $route[0],
				'controller' => $route[1],
				'action' => $route[2],
				'url' => ucfirst($route[1]) . '/' . $route[2]
			];
			return $data;
		}

		/**
		 * 写入修改
		 * @param $data
		 */
		public static function onBeforeInsert($data)
		{
			$data['status'] = 1;
		}

		/**
		 * 写入修改
		 * @param $data
		 */
		public static function onBeforeWrite($data)
		{
			$data['url'] = '';
		}


		protected function setUrlAttr($value, $data)
		{
			return $value ?: $data['controller'] . '/' . $data['action'];
		}

	}
